let allCategories
let task
const urlPrefix = "http://localhost:8080/"
$(document).ready(function () {
    window.pageEvent.onSendTaskDetail((event, param) => {
        task = param.task
        allCategories = param.allCategories
        // 设置表单值
        form.val('detailForm', {
            taskName: task.taskName,
            urls: task.urlList.join("\n"),
            description: task.taskDescription,
            taskDefinition: task.taskDefine,
        });
        // 添加初始类别标签
        if (task.categoryList.length > 0) {
            for (let categoryId of task.categoryList) {
                selectedCategories.add(categoryId)
                addCategoryTag(categoryId, allCategories.get(categoryId))
            }
        }
        // 渲染类别选择器
        const selector = $('#category-selector')
        allCategories.forEach((v, k, m) => {
            selector.append(`<option value="${k}">${v}</option>`)
        })

        form.render('select')
    })

    $('#btn-back').on('click', function () {
        window.pageEvent.switchPage(1, {
            task: task,
            allCategories: allCategories,
        })
    })

    $('#btn-save').on('click', function () {
        task.taskName = $('input[name="taskName"]').val()
        task.taskDescription = $('textarea[name="description"]').val()
        task.urlList = $('textarea[name="urls"]').val().split('\n')
        task.categoryList = Array.from(selectedCategories)
        console.log(task)
        $.ajax({
            url: urlPrefix + "task/update",
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({
                taskId: task.taskId,
                taskName: task.taskName,
                urlList: task.urlList,
                taskDescription: task.taskDescription,
                categoryList: task.categoryList.map(Number),
            }),
            success: function (response) {
                if (response.code !== "200") {
                    layer.msg("任务保存失败：" + response.msg)
                    return
                }
                layer.msg("任务保存成功")
            },
            error: function (xhr, status, error) {
                layer.msg(`任务保存失败，status:${status}, error:${error}`)
            }
        })
    })
})